/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.prashant.sqlduniya.editor;

import java.awt.Color;
import java.awt.Font;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Hashtable;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JTextPane;
import javax.swing.text.DefaultEditorKit;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import org.prashant.sqlduniya.sqlmanager.SQLQuery;
import org.prashant.sqlduniya.sqlmanager.api.QueryChangeListener;

/**
 *
 * @author prashant
 */
public class QueryPanel extends javax.swing.JPanel {

    private SQLQuery sqlQuery;
    private Collection<QueryChangeListener> listeners = new ArrayList<QueryChangeListener>();

    public JTextPane getTxtQueryPane() {
        return txtQueryPane;
    }

    
    /**
     * Utility method for setting the font and color of a JTextPane. The
     * result is roughly equivalent to calling setFont(...) and
     * setForeground(...) on an AWT TextArea.
     */
    public static void setJTextPaneFont(JTextPane jtp, Font font, Color c) {
        // Start with the current input attributes for the JTextPane. This
        // should ensure that we do not wipe out any existing attributes
        // (such as alignment or other paragraph attributes) currently
        // set on the text area.
        MutableAttributeSet attrs = jtp.getInputAttributes();

        // Set the font family, size, and style, based on properties of
        // the Font object. Note that JTextPane supports a number of
        // character attributes beyond those supported by the Font class.
        // For example, underline, strike-through, super- and sub-script.
        StyleConstants.setFontFamily(attrs, font.getFamily());
        StyleConstants.setFontSize(attrs, font.getSize());
        StyleConstants.setItalic(attrs, (font.getStyle() & Font.ITALIC) != 0);
        StyleConstants.setBold(attrs, (font.getStyle() & Font.BOLD) != 0);

        // Set the font color
        StyleConstants.setForeground(attrs, c);

        // Retrieve the pane's document object
        StyledDocument doc = jtp.getStyledDocument();

        // Replace the style for the entire document. We exceed the length
        // of the document by 1 so that text entered at the end of the
        // document uses the attributes.
        doc.setCharacterAttributes(0, doc.getLength() + 1, attrs, false);
    }

    /**
     * Creates new form QueryPanel
     */
    public QueryPanel() {
        initComponents();
        Action actions[] = txtQueryPane.getActions();
        Action cutAction =
                findAction(actions, DefaultEditorKit.cutAction);
        Action copyAction =
                findAction(actions, DefaultEditorKit.copyAction);
        Action pasteAction =
                findAction(actions, DefaultEditorKit.pasteAction);

        JButton cutButton = new JButton(cutAction);
        cutButton.setText("Cut");
        pnlEditorActions.add(cutButton);

        JButton copyButton = new JButton(copyAction);
        copyButton.setText("Copy");
        pnlEditorActions.add(copyButton);

        JButton pasteButton = new JButton(pasteAction);
        pasteButton.setText("Paste");
        pnlEditorActions.add(pasteButton);


    }

    public static Action findAction(Action actions[], String key) {
        Hashtable<Object, Action> commands = new Hashtable<Object, Action>();
        for (int i = 0; i < actions.length; i++) {
            Action action = actions[i];
            commands.put(action.getValue(Action.NAME), action);
        }
        return commands.get(key);
    }

    public SQLQuery getSqlQuery() {
        return sqlQuery;
    }

    public void setSQLQuery(SQLQuery sqlQuery) {
        this.sqlQuery = sqlQuery;
        for (QueryChangeListener theListener : listeners) {
            theListener.queryChanged(sqlQuery);
        }
    }

    public boolean addQueryChangeListener(QueryChangeListener aListener) {
        return this.listeners.add(aListener);
    }

    public boolean removeQueryChangeListener(QueryEditorTopComponent aListener) {
        return this.listeners.remove(aListener);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        txtQueryPane = new javax.swing.JTextPane();
        jToolBar1 = new javax.swing.JToolBar();
        btnRun = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JToolBar.Separator();
        pnlEditorActions = new javax.swing.JPanel();
        jSeparator2 = new javax.swing.JToolBar.Separator();
        btnText2PDF = new javax.swing.JButton();

        setLayout(new java.awt.BorderLayout());

        txtQueryPane.setFont(new java.awt.Font("Courier New", 0, 14)); // NOI18N
        txtQueryPane.setOpaque(false);
        jScrollPane1.setViewportView(txtQueryPane);

        add(jScrollPane1, java.awt.BorderLayout.CENTER);

        jToolBar1.setRollover(true);

        btnRun.setText(org.openide.util.NbBundle.getMessage(QueryPanel.class, "QueryPanel.btnRun.text")); // NOI18N
        btnRun.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRunActionPerformed(evt);
            }
        });
        jToolBar1.add(btnRun);
        jToolBar1.add(jSeparator1);

        pnlEditorActions.setBorder(null);
        jToolBar1.add(pnlEditorActions);
        jToolBar1.add(jSeparator2);

        btnText2PDF.setText(org.openide.util.NbBundle.getMessage(QueryPanel.class, "QueryPanel.btnText2PDF.text")); // NOI18N
        btnText2PDF.setFocusable(false);
        btnText2PDF.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnText2PDF.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnText2PDF.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnText2PDFActionPerformed(evt);
            }
        });
        jToolBar1.add(btnText2PDF);

        add(jToolBar1, java.awt.BorderLayout.PAGE_START);
    }// </editor-fold>//GEN-END:initComponents

    private void btnRunActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRunActionPerformed

        System.out.println("Run " + txtQueryPane.getText());
        System.out.println("Selected Run " + txtQueryPane.getSelectedText());
        String query = txtQueryPane.getSelectedText() != null ? txtQueryPane.getSelectedText()
                : txtQueryPane.getText();
        sqlQuery = new SQLQuery();
        sqlQuery.setSql(query);
        setSQLQuery(sqlQuery);
    }//GEN-LAST:event_btnRunActionPerformed

    private void btnText2PDFActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnText2PDFActionPerformed
//        Graphics2D g2 = cb.createGraphics(612, 792, mapper, true, .95f);
//        AffineTransform at = new AffineTransform();
//        at.translate(convertToPixels(20), convertToPixels(20));
//        at.scale(pixelToPoint, pixelToPoint);
//        g2.transform(at);
//        g2.setColor(Color.WHITE);
//        g2.fill(ta.getBounds());
//        Rectangle alloc = getVisibleEditorRect(ta);
//        ta.getUI().getRootView(ta).paint(g2, alloc);
//        g2.setColor(Color.BLACK);
//        g2.draw(ta.getBounds());
//        g2.dispose();
    }//GEN-LAST:event_btnText2PDFActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnRun;
    private javax.swing.JButton btnText2PDF;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JToolBar.Separator jSeparator2;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JPanel pnlEditorActions;
    private javax.swing.JTextPane txtQueryPane;
    // End of variables declaration//GEN-END:variables
}
